package com.wanmait.happyheating.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wanmait.happyheating.Async.TestAsyncService;
import com.wanmait.happyheating.pojo.*;
import com.wanmait.happyheating.service.*;
import com.wanmait.happyheating.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author 韩丕文
 */
@RestController
@RequestMapping("/userinfo")
public class UserOrderController {
    @Resource
    OrdersinfoService ordersinfoService;

    @Resource
    HeatingNumberService heatingNumberService;

    @Resource
    FaultTypeService faultTypeService;

    @Resource
    ConfigService configService;

    @Resource
    UserinfoService userinfoService;

    @Resource
    AddressService addressService;

    @Resource
    ProvinceService provinceService;

    @Resource
    CityService cityService;

    @Resource
    DistrictService districtService;

    @Resource
    WorkersService workersService;

    @Resource
    StreetService streetService;

    @Resource
    AdminService adminService;

    @Autowired
    TestAsyncService testAsyncService;

    /**
     * 用户下单-韩丕文
     */
    @PostMapping("/placeOrder")
    public Result placeOrder(@RequestBody Ordersinfo ordersinfo) {
        System.out.println("下单用户信息" + ordersinfo);
        LambdaQueryWrapper<Userinfo> userinfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userinfoLambdaQueryWrapper.eq(Userinfo::getName, ordersinfo.getUserName());
        Userinfo userinfoId = userinfoService.getOne(userinfoLambdaQueryWrapper);
        LambdaQueryWrapper<Address> addressLambdaQueryWrapper = new LambdaQueryWrapper<>();
        addressLambdaQueryWrapper.eq(Address::getDetail, ordersinfo.getAddressInfo());
        Address address = addressService.getOne(addressLambdaQueryWrapper);
        ordersinfo.setAddressId(address.getId());
        System.out.println(userinfoId.getId());
        ordersinfo.setUserinfoId(userinfoId.getId());
        if (ordersinfo.getDateTime() != null && ordersinfo.getOrderTimeZone() != null && ordersinfo.getOrderTimeZone() != "") {
            System.out.println("这个怎么可能是空的" + ordersinfo.getOrderTimeZone());
            String orderTimeZone = ordersinfo.getOrderTimeZone().toString();
            StringBuilder checkTime = new StringBuilder();
            checkTime.append(ordersinfo.getDateTime());
            checkTime.append(" ");
            checkTime.append(orderTimeZone.substring(0, 8));
            System.out.println("ordersinfo.getAddressId()"+address.getId());
            System.out.println("String.valueOf(ordersinfo.getAddressInfo())"+String.valueOf(ordersinfo.getAddressInfo()));
            System.out.println("checkTime.toString()"+checkTime.toString());
            List<Workers> workers = workersService.findWorkerByFreeTime(checkTime.toString(), address.getId(), String.valueOf(ordersinfo.getAddressInfo()));
            System.out.println("=====================================================================" + workers);
            if (workers != null) {
                StringBuilder beginTime = new StringBuilder();
                beginTime.append(ordersinfo.getDateTime());
                beginTime.append(" ");
                beginTime.append(orderTimeZone.substring(0, 8));
                StringBuilder endTime = new StringBuilder();
                endTime.append(ordersinfo.getDateTime());
                endTime.append(" ");
                endTime.append(orderTimeZone.substring(9, 17));
                System.out.println(beginTime);
                System.out.println(endTime);
                Timestamp appointmentEndTime = Timestamp.valueOf(endTime.toString());
                Timestamp appointmentStartTime = Timestamp.valueOf(beginTime.toString());
                System.out.println(userinfoId);
                ordersinfo.setAppointmentEndTime(appointmentEndTime);
                ordersinfo.setAppointmentStartTime(appointmentStartTime);
                ordersinfo.setStateId(2);
                ordersinfo.setWorkersId(workers.get(0).getId());
                boolean flag = ordersinfoService.save(ordersinfo);
                if (flag) {
                    redisUtils redis = new redisUtils();
                    System.out.println("不是空不是空不是空不是空不是空" + ordersinfo);
                    WebSocketWithOrdersUtils.sendOrderToWorkerOrAdmin(ordersinfo, workers.get(0));
                    return Result.success("预约添加成功");
                } else {
                    return Result.error("添加失败");
                }
            }
            else{
                return Result.error("已无员工");
            }
        }
        System.out.println("这个怎么可能空"+ordersinfo);

        try {
            if (ordersinfo.getDateTime() != null) {

                ordersinfo.setStateId(1);
                boolean flag = ordersinfoService.save(ordersinfo);
                System.out.println("==========================================");
                if (flag) {
                    Date date = new Date();
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Timestamp timestamp = Timestamp.valueOf(formatter.format(date));
                    Ordersinfo findFirstOrderByEmptyWorker = ordersinfoService.findFirstOrderByEmptyWorker(userinfoId.getId());
                    WebSocketWithOrdersUtils.sendOrderToWorkersWhenGrabbing(findFirstOrderByEmptyWorker, workersService.findWorker(timestamp));
                    int[] taskArrays = new int[]{2000};
                    try {
                        testAsyncService.testNotice(taskArrays, findFirstOrderByEmptyWorker.getId());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    Ordersinfo findFirstOrderByEmptyWorkerTwice = ordersinfoService.findFirstOrderByEmptyWorker(userinfoId.getId());
                    Admin admin = adminService.findAdminByJurisdiction(findFirstOrderByEmptyWorkerTwice.getId());
                    if (findFirstOrderByEmptyWorkerTwice.getWorkersId() == null) {
                        WebSocketWithOrdersUtils.sendOrderToWorkerOrAdmin(findFirstOrderByEmptyWorkerTwice, admin);
                        return Result.success("及时添加成功");
                    }else{
                        return Result.error("添加失败");
                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 是否抢单
     */
//    @Scheduled(fixedRate = 3000)
//    public void run(Ordersinfo ordersinfo,Admin admin){
//
//    }

    /**
     * 通过号码查找地址并返回-韩丕文
     */
    @PostMapping("/findAddressByMas")
    public Result findAddressByMas(@RequestBody Ordersinfo ordersinfo) {
        System.out.println("===================================findAddressBymas");
        System.out.println(ordersinfo.toString());

        LambdaQueryWrapper<HeatingNumber> heatingNumberLambdaQueryWrapper = new LambdaQueryWrapper<>();
        heatingNumberLambdaQueryWrapper.eq(HeatingNumber::getNumber, ordersinfo.getHeatingNumber());
        HeatingNumber address = heatingNumberService.getOne(heatingNumberLambdaQueryWrapper);
        System.out.println(address.toString());

        if (address == null) {
            return Result.error("该账号不存在");
        }
        return Result.success("查询成功", address);
    }


    /**
     * 循环输出所有故障类型-韩丕文
     * 21-5-20
     */
    @PostMapping("findFaultType")
    public Result findFaultType() {
        return Result.success(faultTypeService.list());
    }


    /**
     * 查找工作开始时间工作结束的时间并存入timeZone
     *
     * @return
     */
    @PostMapping("findWorkTime")
    public Result findWorkTime() {
        LambdaQueryWrapper<Config> findWorkEndTime = new LambdaQueryWrapper<>();
        findWorkEndTime.like(Config::getTitle, "worktime_end");
        Config workEndTime = configService.getOne(findWorkEndTime);
        LambdaQueryWrapper<Config> findWorkBeginTime = new LambdaQueryWrapper<>();
        findWorkBeginTime.like(Config::getTitle, "worktime_begin");
        Config workBeginTime = configService.getOne(findWorkBeginTime);
        String endTime = workEndTime.getValue();
        String beginTime = workBeginTime.getValue();
        List<String> timeZone = new ArrayList<>();
        for (int i = Integer.parseInt(beginTime); i < Integer.parseInt(endTime); i++) {
            if (i < 10) {
                String time = i + ":00:00-" + (i + 1) + ":00:00";
                timeZone.add(0 + time);
            } else {
                String time = i + ":00:00-" + (i + 1) + ":00:00";
                timeZone.add(time);
                System.out.println(time);
            }
        }
        return Result.success(timeZone);
    }

    /**
     * 查找工作下午开始时间工作结束的时间并存入timeZonePM
     *
     * @return
     */
    @PostMapping("findWorkTimePm")
    public Result findWorkTimePm() {
        LambdaQueryWrapper<Config> findWorkEndTime = new LambdaQueryWrapper<>();
        findWorkEndTime.like(Config::getTitle, "worktime_end");
        Config workEndTime = configService.getOne(findWorkEndTime);
        String endTime = workEndTime.getValue();
        List<String> timeZone = new ArrayList<>();
        for (int i = 13; i < Integer.parseInt(endTime); i++) {
            String time = i + ":00:00-" + (i + 1) + ":00:00";
            timeZone.add(time);
            System.out.println(time);
        }
        return Result.success(timeZone);
    }

    /**
     * 查找下单时间、
     *
     * @return
     */
    @PostMapping("findOrderDate")
    public Result findOrderDate() {
        LambdaQueryWrapper<Config> findOrderDate = new LambdaQueryWrapper<>();
        findOrderDate.like(Config::getTitle, "order_Date");
        List<Config> orderDate = configService.list(findOrderDate);
        return Result.success(orderDate);
    }

    /**
     * 从token获取用户id 根据用户ID从address表中获取地址
     */
    @PostMapping("findAddressByUserinfo")
    public Result findAddress(@RequestBody Ordersinfo ordersinfo) {
        LambdaQueryWrapper<Userinfo> userinfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userinfoLambdaQueryWrapper.eq(Userinfo::getName, ordersinfo.getUserName());
        Userinfo userinfo = userinfoService.getOne(userinfoLambdaQueryWrapper);
//        Claim userinfoId = UserinfoJWTUtils.getClaimByName(token, "userinfoId");
//        System.out.println("========================================================================="+userinfoId);
//        System.out.println();
        LambdaQueryWrapper<Address> addressLambdaQueryWrapper = new LambdaQueryWrapper<>();
        addressLambdaQueryWrapper.eq(Address::getUserinfoId, userinfo.getId());
        List<Address> addressList = addressService.list(addressLambdaQueryWrapper);
        addressList.forEach(address -> System.out.println(address));
        return Result.success("123", addressList);
    }

    /**
     * 根据时间段查询当前时间段是否有工人空闲
     * (1.0)按照当前日期对比时间段
     */
    @PostMapping("findRightTime")
    public Result findRightTime(@RequestBody Ordersinfo ordersinfo) {
        System.out.println(ordersinfo.getAddressId());
        System.out.println("dateTime:" + ordersinfo.getDateTime());
        System.out.println("od:" + ordersinfo);
        if (ordersinfo.getAddressInfo() == null || ordersinfo.getAddressInfo() == "") {
            LambdaQueryWrapper<Userinfo> userinfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userinfoLambdaQueryWrapper.eq(Userinfo::getName, ordersinfo.getUserName());
            Userinfo userinfoId = userinfoService.getOne(userinfoLambdaQueryWrapper);
            Address address = new Address();
            address.setUserinfoId(userinfoId.getId());
            address.setDetail(String.valueOf(ordersinfo.getAddressInfo()));
            address.setUserinfoId(userinfoId.getId());
            return Result.success(addressService.save(address));
        } else {
            LambdaQueryWrapper<Config> findWorkEndTime = new LambdaQueryWrapper<>();
            findWorkEndTime.like(Config::getTitle, "worktime_end");
            Config workEndTime = configService.getOne(findWorkEndTime);
            LambdaQueryWrapper<Config> findWorkBeginTime = new LambdaQueryWrapper<>();
            findWorkBeginTime.like(Config::getTitle, "worktime_begin");
            Config workBeginTime = configService.getOne(findWorkBeginTime);
            LambdaQueryWrapper<Config> findWorkTimePm = new LambdaQueryWrapper<>();
            findWorkTimePm.like(Config::getTitle, "worktime_Pm");
            Config workTimePm = configService.getOne(findWorkTimePm);
            String pmTime = workTimePm.getValue();
            String endTime = workEndTime.getValue();
            String beginTime = workBeginTime.getValue();
            Date date = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            System.out.println("===========================================================================" + formatter.format(date));
            List<String> timeZone = new ArrayList<>();
            if (ordersinfo.getDateTime().equals(formatter.format(date))) {
                for (int i = Integer.parseInt(pmTime); i < Integer.parseInt(endTime); i++) {
                    String time = i + ":00:00-" + (i + 1) + ":00:00";
                    timeZone.add(time);

                }
            } else {
                for (int i = Integer.parseInt(beginTime); i < Integer.parseInt(endTime); i++) {
                    if (i < 10) {
                        String time = i + ":00:00-" + (i + 1) + ":00:00";
                        System.out.println(i);
                        timeZone.add(0 + time);
                    } else {
                        String time = i + ":00:00-" + (i + 1) + ":00:00";
                        timeZone.add(time);
                    }

                }
            }
            /**
             *
             */
            List<String> timeList = new ArrayList<>();
            for (String s : timeZone) {
                StringBuilder checkTime = new StringBuilder();
                checkTime.append(ordersinfo.getDateTime());
                System.out.println("ordersinfo.getDateTime()" + ordersinfo.getDateTime());
                checkTime.append(" ");
                checkTime.append(s);
                timeList.add(checkTime.toString());
            }
            System.out.println(timeList);
            TreeMap freeWorkers = new TreeMap();
            for (int i = 0; i < timeList.size(); i++) {
                List<Workers> workers = workersService.findWorkerByFreeTime(timeList.get(i), ordersinfo.getAddressId(), String.valueOf(ordersinfo.getAddressInfo()));
                System.out.println(workers);
                System.out.println("============================================================================================" + timeList.get(i));
                String time = timeList.get(i).substring(10, 28);
                freeWorkers.put(time, workers);
            }
            List<String> freeTime = new ArrayList<>();
            Iterator it = freeWorkers.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry entry = (Map.Entry) it.next();
                if (entry.getValue() != null) {
                    freeTime.add(entry.getKey().toString());
                }
            }
            System.out.println("===================================================订单时间===============================================");
            System.out.println(freeWorkers);
            freeTime.forEach(s -> System.out.println(s));
            return Result.success(freeWorkers);
        }

    }


    /**
     * 根据下单时间二次查询是否有空闲工作人员
     */
    @PostMapping("checkFreeTimeAgain")
    public Result checkFreeTimeAgain(@RequestBody Ordersinfo ordersinfo) {
        String orderTimeZone = ordersinfo.getOrderTimeZone().toString();
        System.out.println(ordersinfo.getAddressId());
        StringBuilder checkTime = new StringBuilder();
        checkTime.append(ordersinfo.getDateTime());
        checkTime.append(" ");
        checkTime.append(orderTimeZone.substring(0, 8));
        List<Workers> workers = workersService.findWorkerByFreeTime(checkTime.toString(), ordersinfo.getAddressId(), String.valueOf(ordersinfo.getAddressInfo()));
        System.out.println(workers);
        return Result.success("下单成功");
    }

    /**
     * 省市联动
     */
    @PostMapping("selectAllProvince")
    public Result selectAllProvince() {
        return Result.success(provinceService.list());
    }

    @PostMapping("findCityByProvinceId")
    public Result findCityByProvinceId(@RequestBody Province province) {
        LambdaQueryWrapper<City> cityLambdaQueryWrapper = new LambdaQueryWrapper<>();
        cityLambdaQueryWrapper.eq(City::getProvinceId, province.getId());
        List<City> cityList = cityService.list(cityLambdaQueryWrapper);
        return Result.success(cityList);
    }

    @PostMapping("findDistrictByCityId")
    public Result findDistrictByCityId(@RequestBody City city) {
        LambdaQueryWrapper<District> districtLambdaQueryWrapper = new LambdaQueryWrapper<>();
        districtLambdaQueryWrapper.eq(District::getCityId, city.getId());
        List<District> districtList = districtService.list(districtLambdaQueryWrapper);
        return Result.success(districtList);
    }

    @PostMapping("findStreetByDistrictId")
    public Result findStreetByDistrictId(@RequestBody District district) {
        LambdaQueryWrapper<Street> streetLambdaQueryWrapper = new LambdaQueryWrapper<>();
        streetLambdaQueryWrapper.eq(Street::getDistrictId, district.getId());
        List<Street> districtList = streetService.list(streetLambdaQueryWrapper);
        return Result.success(districtList);
    }

    /**
     * 通过地址向上返回省市联动
     *
     * @param ordersinfo
     * @return
     */
    @PostMapping("findProvincialAndMunicipaLinkageByAddress")
    public Result findProvincialAndMunicipaLinkageByAddress(@RequestBody Ordersinfo ordersinfo) {
        HashMap hashMap = new HashMap();

        LambdaQueryWrapper<Address> addressLambdaQueryWrapper = new LambdaQueryWrapper<>();
        addressLambdaQueryWrapper.eq(Address::getDetail, ordersinfo.getAddressInfo());
        Address address = addressService.getOne(addressLambdaQueryWrapper);
        if (address != null) {
            LambdaQueryWrapper<Street> streetLambdaQueryWrapper = new LambdaQueryWrapper<>();
            streetLambdaQueryWrapper.eq(Street::getId, address.getId());
            Street street = streetService.getOne(streetLambdaQueryWrapper);
            hashMap.put("street", street.getId());

            LambdaQueryWrapper<District> districtLambdaQueryWrapper = new LambdaQueryWrapper<>();
            districtLambdaQueryWrapper.eq(District::getId, street.getDistrictId());
            District district = districtService.getOne(districtLambdaQueryWrapper);
            hashMap.put("district", district.getId());

            LambdaQueryWrapper<City> cityLambdaQueryWrapper = new LambdaQueryWrapper<>();
            cityLambdaQueryWrapper.eq(City::getId, district.getCityId());
            City city = cityService.getOne(cityLambdaQueryWrapper);
            hashMap.put("city", city.getId());

            LambdaQueryWrapper<Province> provinceLambdaQueryWrapper = new LambdaQueryWrapper<>();
            provinceLambdaQueryWrapper.eq(Province::getId, city.getProvinceId());
            Province province = provinceService.getOne(provinceLambdaQueryWrapper);
            hashMap.put("province", province.getId());


            return Result.success(hashMap);
        } else {
            return Result.error("改地址未收录");
        }

    }


    /**
     * 生成新地址
     */
    @PostMapping("insertNewAddress")
    public Result insertNewAddress(@RequestBody Ordersinfo ordersinfo, Integer streetId) {
//        Claim userinfoId = UserinfoJWTUtils.getClaimByName(token, "userinfoId");
        LambdaQueryWrapper<Userinfo> userinfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userinfoLambdaQueryWrapper.eq(Userinfo::getName, ordersinfo.getUserName());
        Userinfo userinfoId = userinfoService.getOne(userinfoLambdaQueryWrapper);
        System.out.println(userinfoId.getId());
        Address address = new Address();
        address.setDetail((String) ordersinfo.getAddressInfo());
        address.setStreetId(streetId);
        address.setDefaultAddress(false);
        address.setEnable(true);
        address.setUserinfoId(userinfoId.getId());
        addressService.save(address);
        return Result.success();
    }

    @PostMapping("findUserinfo")
    public Result findUserinfo(@RequestBody Ordersinfo ordersinfo) {
        LambdaQueryWrapper<Userinfo> userinfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userinfoLambdaQueryWrapper.eq(Userinfo::getName, ordersinfo.getUserName());
        Userinfo userinfo = userinfoService.getOne(userinfoLambdaQueryWrapper);
        return Result.success(userinfo);
    }


}
